//
//  XJNetworkTools.swift
//  XJWeiBO
//
//  Created by 452608533 on 16/7/22.
//  Copyright © 2016年 452608533. All rights reserved.
//

import UIKit
import AFNetworking

enum XJNetworkToolsType: String{
    
    case GET = "GET"
    case POST = "POST"
}

class XJNetworkTools: AFHTTPSessionManager {
    
    //设置全局访问点
    
    static let sharedTools: XJNetworkTools = {
        
        let tools = XJNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    func request(type: XJNetworkToolsType, urlString: String,paremeters:AnyObject?, success:((response:AnyObject?)->()),failure:((error: NSError)->())){
        
        if type == .GET {
            
            GET(urlString, parameters: paremeters, progress: nil, success: { (_, res) -> Void in
                
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
            
        }else{
            
            POST(urlString, parameters: paremeters, progress: nil, success: { (_, res) -> Void in
                
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }
    }
}
//请求OAuth界面数据
extension XJNetworkTools{
    
    func oauthLoadUserAccount(code: String, success:((response:AnyObject?)->()),failure:((error: NSError)->())) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let para = [
            "client_id" : APPKEY,
            "client_secret" : APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : APPREDIRECT_URI
        ]
        request(XJNetworkToolsType.POST, urlString: urlString, paremeters: para, success: success, failure: failure)
    }
    //请求用户信息
    func oauthLoadUserInfo(userAccount: XJUserAccount, success:((response:AnyObject?)->()),failure:((error: NSError)->())) {
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid!
        ]
        request(.GET, urlString: urlString, paremeters: params, success: success, failure: failure)
    }
}

//主界面请求信息
extension XJNetworkTools{
    
    func homeLoadData(sinceId: Int64, maxId: Int64, success:((response:AnyObject?)->()),failure:((error: NSError)->())) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let param = ["access_token":XJUserAccountViewModel.sharedTools.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"
        ]
        
        request(XJNetworkToolsType.GET, urlString: urlString, paremeters: param, success:success, failure: failure)
    }
    
}











